package com.cu.redission.service.impl;

import com.cu.redission.entity.User;
import com.cu.redission.mapper.UserMapper;
import com.cu.redission.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean addTest() {
        RLock rLock = redissonClient.getLock("name");
        try {
            boolean lockResult = rLock.tryLock(100, 8, TimeUnit.MILLISECONDS);
            if (lockResult) {
                try {
                    // 加锁成功，执行业务逻辑
                    User user = new User();
                    user.setName("name");
                    user.setAge(11);
                    userMapper.insert(user);
                } catch (Exception e) {
                    return false;
                } finally {
                    rLock.unlock();
                }
            } else {
                // 加锁失败处理逻辑
                return false;
            }
        } catch (InterruptedException e) {
            // 处理中断异常
            Thread.currentThread().interrupt(); // 保留中断状态
            e.printStackTrace();
        }
        return false;
    }
}
